package com.study_security.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study_security.dto.ProjectDTO;
import com.study_security.dto.ProjectFormDTO;
import com.study_security.entity.Project;
import com.study_security.mapper.ProjectMapper;
import com.study_security.service.ProjectService;
import com.study_security.utils.CacheClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.study_security.dto.ProjectOutputDTO;
import com.study_security.dto.TaskDetailDTO;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

import static com.study_security.utils.RedisConstants.PROJECT_KEY;


@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private CacheClient cacheClient;
    @Override
    public List<Project> getOngoingProjects(Long userId) {
        return projectMapper.selectOngoingProjects(userId);
    }

    @Override
    public List<Project> getCompletedProjects(Long userId) {
        return projectMapper.selectCompletedProjects(userId);
    }

    @Override
    public List<Project> getAllProject() {
        return projectMapper.getAllProject();
    }

    @Override
//    public List<Project> searchOngoingProjects(Long userId,String keyword) {
//        return projectMapper.searchOngoingProjects(userId,keyword);
//    }
    public List<Project> searchOngoingProjects(Long userId, String keyword, String projectType, String importantLevel, String sortBy) {
        return projectMapper.searchOngoingProjects(userId, keyword, projectType, importantLevel, sortBy);
    }

    @Override
    public List<Project> searchCompletedProjects(Long userId,String keyword) {
        return projectMapper.searchCompletedProjects(userId,keyword);
    }

    @Override
    public boolean addProject(Long userId,Project project) {
        return projectMapper.insert(project) > 0;
    }

    @Override
    public boolean projectNameExists(String projectName) {
        return projectMapper.countByProjectName(projectName) > 0;
    }
    @Override
    public List<ProjectDTO> getUserProjects(Long userId) {
        return projectMapper.selectUserProjects(userId);
    }

    @Override
    public Project getProjectById(Long projectId) {
        return projectMapper.selectProjectById(projectId);
    }

    @Override
    public List<Project> getAllProjects() {
        return projectMapper.selectAllProject();
    }

    @Override
    public List<ProjectFormDTO> getAllProjectFormDTOByUserId(Long userId) {
        return cacheClient.queryWithPassThrough(
                PROJECT_KEY,
                userId,
                List.class, // 返回类型是 List<ProjectFormDTO>
                id -> projectMapper.selectAllProjectFormDTOByUserId(id), // 数据库查询回退逻辑
                2L,
                TimeUnit.MINUTES,
                ProjectFormDTO.class
        );
       // return projectMapper.selectAllProjectFormDTOByUserId(userId);
    }

    @Override
    public List<Project> getAllProjectByUserId(Long userId) {
        return projectMapper.selectAllProjectByUserId(userId);
    }

    @Override
    public List<ProjectFormDTO> getAllProjectFormDTO() {
        return projectMapper.selectAllProjectFormDTO();
    }


    @Override
    public List<Project> getFilteredProjects(String endDateAfter, String startDateAfter, BigDecimal contractAmountGt) {
        return projectMapper.getFilteredProjects(endDateAfter, startDateAfter, contractAmountGt);
    }

    @Override
    public List<Project> getFilteredProjectsByUserId(Long userId, String endDateAfter, String startDateAfter, BigDecimal contractAmountGt) {
        return projectMapper.getFilteredProjectsByUserId(userId, endDateAfter, startDateAfter, contractAmountGt);
    }


    private Date parseDate(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            // 记录日志或抛出自定义异常
            return null;
        }
    }



    @Override
    public ProjectOutputDTO getProjectOutputByName(String projectName) {
        // 获取项目基本信息
        Project project = projectMapper.getProjectByName(projectName);
        if (project == null) {
            return null;
        }

        BigDecimal contractAmount = project.getContractAmount();
        BigDecimal fixedCost = project.getCost() != null ? project.getCost() : BigDecimal.ZERO; // cost属性为固定成本

        // 获取项目的所有任务，按照startDate排序，并包含任务开始日期和负责人月薪
        List<TaskDetailDTO> taskDetails = projectMapper.getTasksWithDetailsByProjectName(projectName);
        if (taskDetails == null || taskDetails.isEmpty()) {
            return null;
        }

        List<String> startDates = new ArrayList<>();
        List<BigDecimal> contractAmounts = new ArrayList<>();
        List<BigDecimal> outputValues = new ArrayList<>();
        List<BigDecimal> totalCosts = new ArrayList<>();

        BigDecimal cumulativePersonnelCost = BigDecimal.ZERO;

        for (TaskDetailDTO task : taskDetails) {
            startDates.add(task.getStartDate());
            contractAmounts.add(contractAmount);
            BigDecimal hourlyWage = new BigDecimal(Math.ceil(task.getMonthlySalary().doubleValue() / 170));

            // 计算任务成本 = 每小时工资 * 工时
            BigDecimal taskCost = hourlyWage.multiply(new BigDecimal(task.getWorkHours()));

            // 累计人员成本
            cumulativePersonnelCost = cumulativePersonnelCost.add(taskCost);

            // 总成本 = 人员成本 + 固定成本
            BigDecimal totalCost = cumulativePersonnelCost.add(fixedCost);
            totalCosts.add(totalCost);

            // 计算产值 = 合同额 - 总成本
            BigDecimal outputValue = contractAmount.subtract(totalCost);
            outputValues.add(outputValue);
        }

        ProjectOutputDTO projectOutputDTO = new ProjectOutputDTO();
        projectOutputDTO.setStartDate(startDates);
        projectOutputDTO.setContractAmount(contractAmounts);
        projectOutputDTO.setOutputValue(outputValues);
        projectOutputDTO.setTotalCost(totalCosts);
        projectOutputDTO.setTasks(taskDetails);

        return projectOutputDTO;
    }

}
